package cn.gailvlun.gll.presentation.emotion.edit;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.widget.NestedScrollView;
import android.text.InputFilter;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

import com.blankj.utilcode.util.KeyboardUtils;
import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding2.widget.RxRadioGroup;
import com.jakewharton.rxbinding2.widget.RxTextView;

import java.util.List;

import cn.gailvlun.gll.R;
import cn.gailvlun.gll.databinding.ActivityEmotionRecordBinding;
import cn.gailvlun.gll.mgr.UploadResult;
import cn.gailvlun.gll.net.emotion.EmotionEnum;
import cn.gailvlun.gll.net.emotion.EmotionTagReq;
import cn.gailvlun.gll.net.emotion.FilterEnum;
import cn.gailvlun.gll.presentation.base.BaseActivity;
import cn.gailvlun.gll.presentation.chat.PhotoActivity;
import cn.gailvlun.gll.presentation.emotion.photo.PhotoPicker;
import cn.gailvlun.gll.presentation.emotion.util.LengthFilter;
import cn.gailvlun.gll.util.DensityUtil;
import cn.gailvlun.gll.widget.NavigationBarView;
import cn.gailvlun.gll.widget.photopicker.PhotoItem;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Predicate;
import rx_activity_result2.Result;
import rx_activity_result2.RxActivityResult;

import static cn.gailvlun.gll.presentation.emotion.edit.SelectEmotionTagActivityKt.EMOTION_TAG_REQ;


public class EmotionRecordActivity extends BaseActivity {
    private ActivityEmotionRecordBinding mBinding;
    private Window mWindow;
    private int offset;
    
    private boolean isEditTextScrolled = false;
    private DraftDialog mDraft;
    private String mText;
    private List<PhotoItem> mPhotoItemList;
    private EmotionEnum mEmotionEnum;
    private FilterEnum mFilterEnum;
    private EmotionRecordViewModel mViewModel;
    private EmotionTagReq mEmotionTagReq;


    public static void openActivity(Context context) {
        Intent i = new Intent(context, EmotionRecordActivity.class);
        context.startActivity(i);
    }

    public static void openActivity(Activity context, Consumer<Result<Activity>> resultConsumer) {
        Intent intent = new Intent(context, EmotionRecordActivity.class);
        RxActivityResult.on(context)
                .startIntent(intent)
                .subscribe(resultConsumer);
    }

    public static void openActivity(Activity context, EmotionTagReq emotionTagReq, Consumer<Result<Activity>> resultConsumer) {
        Intent intent = new Intent(context, EmotionRecordActivity.class);
        intent.putExtra(EMOTION_TAG_REQ, emotionTagReq);
        RxActivityResult.on(context)
                .startIntent(intent)
                .subscribe(resultConsumer);
    }

    @Override
    protected void initComponent() {
        mWindow = getWindow();
        mWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_emotion_record);
        mViewModel = new EmotionRecordViewModel(mContext);
        mBinding.setVm(mViewModel);
        mBinding.cevContent.setFilters(new InputFilter[]{new LengthFilter(4000)});
    }

    @Override
    protected void createHandler() {
        mBinding.navigationBar.setOnBackListener(new NavigationBarView.OnBackListener() {
            @Override
            public void onBack(NavigationBarView nb) {
                onBackPressed();
            }
        });
        mBinding.navigationBar.setOnMenuClickListener(new NavigationBarView.OnMenuClickListener() {
            @Override
            public void onMenuClick(NavigationBarView nb) {
                mText = mBinding.cevContent.getText().toString().trim();
                mPhotoItemList = mBinding.photoPicker.getFileList();
                EmotionPostDialog dialog = EmotionPostDialog.Companion.newInstance();
                dialog.showIfNeed3(mContext,mFilterEnum, mViewModel.getEmotionTagReq(), mText, mPhotoItemList);
            }
        });
































        RxRadioGroup.checkedChanges(mBinding.rg)
                .filter(new Predicate<Integer>() {
                    @Override
                    public boolean test(Integer checkedId) throws Exception {
                        switch (checkedId) {
                            case R.id.rb_one:
                                mFilterEnum = FilterEnum.P;
                                break;
                            case R.id.rb_tow:
                                mFilterEnum = FilterEnum.N;
                                break;
                            case R.id.rb_three:
                                mFilterEnum = FilterEnum.X;
                                break;
                        }

                        return checkedId != -1;
                    }
                })
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) throws Exception {


                    }
                });

        RxTextView.textChanges(mBinding.cevContent)
                .subscribe(new Consumer<CharSequence>() {
                    @Override
                    public void accept(CharSequence charSequence) throws Exception {
                        postButtonEnable();
                    }
                });

        showEditTextAnimation();
        showPhotoPickerAnimation();
    }

    private void showEditTextAnimation() {
        KeyboardUtils.registerSoftInputChangedListener(this, new KeyboardUtils.OnSoftInputChangedListener() {
            @Override
            public void onSoftInputChanged(int height) {
                if (!KeyboardUtils.isSoftInputVisible(mContext)) {


                    isEditTextScrolled = false;
                    mBinding.ibHideSoftinput.setVisibility(View.GONE);
                }
            }
        });











        mBinding.cevContent.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (v.getId() == R.id.cev_content) {
                    v.getParent().requestDisallowInterceptTouchEvent(true);
                    switch (event.getAction() & MotionEvent.ACTION_MASK) {
                        case MotionEvent.ACTION_UP:
                            v.getParent().requestDisallowInterceptTouchEvent(false);
                            break;
                    }
                }
                return false;
            }
        });
        mBinding.svOutside.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (isEditTextScrolled) {
                    if (isSoftShowing()) {
                        KeyboardUtils.hideSoftInput(mBinding.cevContent);
                    }
                }
            }
        });


    }

    private void pushEditTextToTop() {
        if (!mBinding.cevContent.isFocusable()) {
            mBinding.cevContent.setFocusableInTouchMode(true);
            mBinding.cevContent.setFocusable(true);
            int scrollY = mBinding.svOutside.getScrollY();
            int height = mBinding.llEmotionState.getHeight();
            if (!isSoftShowing()) {
                offset = height;
                ObjectAnimator animator = ObjectAnimator.ofInt(mBinding.svOutside, "scrollY", offset).setDuration(200L);
                animator.addListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        super.onAnimationEnd(animation);
                        isEditTextScrolled = true;
                    }
                });

                animator.start();
                KeyboardUtils.showSoftInput(mBinding.cevContent);

            }
        }
    }

    private void pullEditTextToOrigin() {
        if (isSoftShowing()) {
            ObjectAnimator.ofInt(mBinding.svOutside, "scrollY", -offset).start();
            KeyboardUtils.hideSoftInput(mBinding.cevContent);
        }
    }

    private void showPhotoPickerAnimation() {
        mBinding.photoPicker.setOnUploadMgrListener(new PhotoPicker.OnUploadMgrListener() {
            @Override
            public void onNext(UploadResult uploadResult) {

            }

            @Override
            public void onError(Throwable t) {

            }

            @Override
            public void onComplete() {
                mBinding.photoPicker.setVisibility(View.VISIBLE);

                postButtonEnable();

            }
        });

        mBinding.photoPicker.setOnCloseListener(new PhotoPicker.OnCloseListener() {
            @Override
            public void onClose(PhotoItem photoItem) {
                mBinding.photoPicker.removePhotoItem(photoItem);
                postButtonEnable();
            }
        });


        RxView.clicks(mBinding.ibAddPictures)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        mBinding.photoPicker.getPresenter().onAdd();
                        if (isSoftShowing()) {
                            KeyboardUtils.hideSoftInput(mBinding.cevContent);
                        }

                    }
                });







        mBinding.photoPicker.setOnPhotoClickListener(new PhotoPicker.OnPhotoClickListener() {
            @Override
            public void onPhotoClick(ImageView iv, String file) {
                ActivityOptionsCompat options = ActivityOptionsCompat
                        .makeSceneTransitionAnimation(mContext, iv, getString(cn.gailvlun.gll.chatkit.R.string.shared_image));
                PhotoActivity.openActivity(mContext, file, options.toBundle());
            }
        });
    }

    private void postButtonEnable() {
        if (mBinding.photoPicker.getFileList().size() == 0 && mBinding.cevContent.length() == 0) {
            mBinding.navigationBar.setMenuTextColor(R.color.pinkishGrey);
            mBinding.navigationBar.setMenuEnable(false);
        } else {
            mBinding.navigationBar.setMenuTextColor(R.color.white);
            mBinding.navigationBar.setMenuEnable(true);
        }
    }


    
    private boolean isSoftShowing() {
        final int SOFT_KEYBOARD_HEIGHT_DP_THRESHOLD = 128;

        
        int screenHeight = mContext.getWindow().getDecorView().getHeight();
        
        Rect rect = new Rect();
        mContext.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);

        return Math.abs(screenHeight - rect.bottom) > DensityUtil.dp2px(mContext,
                SOFT_KEYBOARD_HEIGHT_DP_THRESHOLD);
    }


    @Override
    protected void loadData(@Nullable Bundle savedInstanceState) {
        mDraft = new DraftDialog();
        mEmotionTagReq = getIntent().getParcelableExtra(EMOTION_TAG_REQ);
        if (mEmotionTagReq != null) {
            mViewModel.setEmotionTagReq(mEmotionTagReq);
            mViewModel.getEmotionState().set(mEmotionTagReq.getEmotionState());
            mViewModel.getEmotionTagTitle().set(mEmotionTagReq.getTitle());
            mViewModel.isClick().set(false);
        }

        DraftDialog.Draft draft = mDraft.restoreDraft(mBinding);
        if (draft != null) {
            mEmotionEnum = draft.emotionEnum;
            mText = draft.text;
            mPhotoItemList = draft.photoItemList;
        }
    }


    @Override
    public void onBackPressed() {
        mText = mBinding.cevContent.getText().toString().trim();
        mPhotoItemList = mBinding.photoPicker.getFileList();
        mDraft.showIfNeed(mContext, mEmotionEnum, mText, mPhotoItemList);
        if (isSoftShowing()) {
            KeyboardUtils.hideSoftInput(mBinding.cevContent);
        }
    }


}
